# -*- coding:utf-8 -*-
import os,sys
import re
import traceback
import time
from mylog import mylog
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
import supeanut_config
from db.MongoDBTool import MongoDBTool


'''
作者：supeanut
创建时间：2016-12-12 21:56
功能描述：
	股票基本信息获取工具类
相关配置：
	supeanut_config.StockTool csv file
历史改动：
	2016-12-11 修改个股代码的市场判定
	2016-12-12 新增指数前缀规范（新浪）
	2016-12-13 根据local csv文件获取股票代码
'''
class StockTool:
	# init what
	def __init__(self):
		self.stockinfo_csv_path = supeanut_config.STOCKINFO_CSV_PATH
		self.stockinfo_csv_name = supeanut_config.STOCKINFO_CSV_FILE
		self.index_code = supeanut_config.INDEX_CODE
		self.calendar_csv_path = supeanut_config.CALENDAR_CSV_PATH
		self.calendar_csv_name = supeanut_config.CALENDAR_CSV_FILE
		self.field_code_index = supeanut_config.STOCKINFO_DATAYES_CODE
		self.field_status_index = supeanut_config.STOCKINFO_DATAYES_STATUS
		self.field_tradedate_index = supeanut_config.CALENDAR_DATAYES_DATE_INDEX
		self.field_isopen_index = supeanut_config.CALENDAR_DATAYES_ISOPEN_INDEX

	# 根据交易日历，获取股票的停牌日期
	# 输入"600000"
	def getStopDates(self, code, ):
		mongo = MongoDBTool()
		db_name = supeanut_config.MONGO_DB
		day_coll = supeanut_config.MONGO_COLL_DAYDATA
		mongo.conn(db_name, day_coll)
		flag, cal_dates = self.get_trade_date()
		if flag is False:
			return False, None
		code_dates_iter = mongo.coll.find(filter={'code':self.get_stock_market(code)+code},projection=['date'])
		code_dates = []
		for code_date in code_dates_iter:
			code_dates.append(code_date['date'])
		code_dates.sort()
		if len(code_dates) == 0:
			return True, []
		code_date_s = code_dates[0]
		i = 0
		find_s_tag = False
		for cal_date in cal_dates:
			i += 1
			if cal_date == code_date_s:
				find_s_tag = True
				break
		if find_s_tag is False:
			return False, None
		stop_dates = []
		for j in range(0, len(code_dates)):
			cal_date = cal_dates[j+i-1]
			code_date = code_dates[j]
			if cal_date == code_date:
				continue
			elif cal_date > code_date:
				return False, None
			else:
				temp_stop_dates = [cal_date]
				k = 1
				tag = False
				while cal_date < code_date:
					cal_date = cal_dates[j+i-1+k]
					temp_stop_dates.append(cal_date)
					if cal_date == code_date:
						i += k
						tag = True
						break
					if cal_date > code_date:
						return False, None
					k += 1
				if tag is False:
					return False, None
				else:
					stop_dates.extend(temp_stop_dates[:-1])
		return True, stop_dates


	# 输入个股代码（非指数）
	# 返回sz 或 sh
	def get_stock_market(self, stock_code):
		if stock_code[0] == '6':
			return 'sh'
		else:
			return 'sz'
	
	# 新浪接口的指数请求规范
	def get_sina_index_market(self, index_code):
		if index_code[:3] == '399':
			return 'sz'
		else:
			return 'sh'

	# WS代码转为标准代码
	# SH,SZ333333 --> sh,sz,in000001
	def ws_code2stand_code(self, ws_str):
		ws_index = ['sh000001','sh000300','sz399005','sz399001','sz399006']
		ws_market = ws_str[:2].lower()
		ws_code = ws_str[2:]
		ws_market_code = ws_market + ws_code
		if ws_market_code in ws_index:
			ws_market_code = 'in' + ws_code
		return ws_market_code

	# 获取所有标准代码，包括index,包括退市的
	# 带前缀
	def get_all_stand_codes(self, ):
		all_code = []
		for index in self.index_code:
			all_code.append('in'+index)
		flag, msg = self.get_all_stock_code('all')
		if flag is False:
			return False, msg
		for code in msg:
			code_market = self.get_stock_market(code)
			all_code.append(code_market + code)
		return True, all_code
	
	# 获取当前市场所有股票代码(6位代码)
	# L: 正常上市状态
	# all: 所有状态
	def get_all_stock_code(self, status):
		comp_path = os.path.join(self.stockinfo_csv_path, self.stockinfo_csv_name)
		if not os.path.exists(comp_path):
			return False, 'no such csv file'
		try:
			file_info = open(comp_path, 'rb')
			stockinfo = file_info.readlines()
			file_info.close()
		except:
			return False, 'open file failed'
		stock_list = []
		for onestock_str in stockinfo:
			split_list = onestock_str.split(',')
			# 
			stock_code = split_list[self.field_code_index]
			stock_status = split_list[self.field_status_index]
			if status == 'all':
				stock_list.append(stock_code)
			elif stock_status == status:
				stock_list.append(stock_code)
			else:
				pass
		return True, stock_list


	# 获取若干重要指数代码
	def get_import_index_code(self, ):
		return self.index_code
		
	# 获取区间交易日
	# 未指定则默认最前或最后
	def get_trade_date(self, s_date='', e_date=''):
		comp_path = os.path.join(self.calendar_csv_path, self.calendar_csv_name)
		if not os.path.exists(comp_path):
			return False, 'no such csv file'
		try:
			file_info = open(comp_path, 'rb')
			dateinfo = file_info.readlines()
			file_info.close()
		except:
			return False, 'open file failed'
		all_trade_date = []
		for onedate_str in dateinfo:
			split_list = onedate_str.split(',')
			if split_list[self.field_isopen_index] == '1':
				all_trade_date.append(split_list[self.field_tradedate_index])
		all_trade_date.sort()
		if s_date == '' and e_date == '':
			return True, all_trade_date
		s_index = 0
		e_index = len(all_trade_date) - 1
		if e_date <> '':
			while all_trade_date[e_index] > e_date:
				e_index -= 1
				if e_index < 0:
					break
		if s_date <> '':
			while all_trade_date[s_index] < s_date:
				s_index += 1
				if s_index > e_index:
					break
		if s_index > e_index:
			return True, []
		return True, all_trade_date[s_index: e_index + 1]

	# csv版本
	# 返回个股和指数的代码（sz300033、in000001形式）
	# L和DE和S状态
	def get_all_stockindex_code_bycsv(self, ):
		all_codes = []
		index_codes = self.get_import_index_code()
		for index in index_codes:
			all_codes.append('in'+index)
		flag, msg = self.get_all_stock_code('L')
		if flag is False:
			return False, msg
		for code in msg:
			all_codes.append(self.get_stock_market(code) + code)
		flag, msg = self.get_all_stock_code('S')
		if flag is False:
			return False, msg
		for code in msg:
			all_codes.append(self.get_stock_market(code) + code)
		flag, msg = self.get_all_stock_code('DE')
		if flag is False:
			return False, msg
		for code in msg:
			all_codes.append(self.get_stock_market(code) + code)
		return True, all_codes



if __name__ == '__main__':
	obj = StockTool()
	#print obj.get_all_stock_code('all')
	#print obj.get_all_stock_code('L')
	#print obj.get_import_index_code()
	#flag,msg = obj.get_all_stockindex_code()
	#print obj.get_trade_date('2016-12-12', '')
	print obj.getStopDates('sz300033')
